#!/usr/bin/perl -w

package Purl::DB::Flatfile;

use strict;

sub load {
	my($objects, $id, $dbVersion, $dbVersionKnown);
	if (!CORE::open(IN, $main::dbFile)) {
		print "Unable to read from " . $main::dbFile . ".\n";
		print "Please read the documentation and follow\n";
		print "all of the instructions carefully.\n";
		exit 0;
	}
	$dbVersionKnown = 0;
	while($id = <IN>) {
		if (!$dbVersionKnown) {
			$dbVersionKnown = 1;
			if (!($id =~ /^\d+\.\d+\s*$/)) {
				$dbVersion = 0.0;
			} else {
				$dbVersion = $id;
				if ($dbVersion > $main::Version) {
					print "This database was written by a newer version of PurlMUSH!\nYou need version $dbVersion to read it.\n";
					close(IN);
					exit 0;	
				}
				next;	
			}
		}
		chomp $id;
		while (1) {
			my($attribute, $value, $line);
			$line = <IN>;
			if ($line eq "") {
				#Uh-oh
				print "Database is truncated!\n";
				return 0;
			}
			chomp $line;
			if ($line eq "<END>") {
				last;
			}
			# Get the attribute and the value
			($attribute, $value) = split(/ /, $line, 2);  
			# Unescape endlines
			$value =~ s/\\n/\r\n/g;
			# But a slash preceding one of those means an escaped LF is truly wanted
			$value =~ s/\\\r\n/\\n/g;
			$main::objects[$id]{$attribute} = $value;
		}
		$main::objects[$id]{"id"} = $id;
	}
	close(IN);
	return \@main::objects;
}

sub verify {
   my $objects = shift;
   foreach my $id (@{$objects}) {
      if ($id == 1) {
         ${$main::objects}[$id]{"flags"} |= $main::flags{"wizard"}{"value"};
      }
      if (($main::objects[$id]{"type"} == $main::player) || ($main::objects[$id]{"flags"} & $main::flags{"creature"}{"value"})) {
         my $n = $main::objects[$id]{"name"};
         $n =~ tr/A-Z/a-z/;
         $main::objects[$id]{"activeFd"} = $main::none;
         $main::playerIds{$n} = $id;
      }
   return 1;
   }
} 
1;
